package top.hooray.delayedpayment.service.impl;

import org.springframework.stereotype.Service;
import top.hooray.delayedpayment.entity.Order;
import top.hooray.delayedpayment.entity.OrderStatus;
import top.hooray.delayedpayment.repository.OrderRepository;
import top.hooray.delayedpayment.service.OrderService;

import java.util.Optional;

/**
 * @author hooray
 * @date 2021/3/9 22:58
 */
@Service
public class OrderServiceImpl implements OrderService {

    private final OrderRepository orderRepository;

    public OrderServiceImpl(OrderRepository orderRepository) {
        this.orderRepository = orderRepository;
    }

    @Override
    public void saveOrder(Order order) {
        orderRepository.save(order);
    }

    @Override
    public void updateOrderStatus(Long orderId, OrderStatus orderStatus) {
        Optional<Order> optional = orderRepository.findById(orderId);
        optional.ifPresent(order -> {
            if (OrderStatus.UNPAID.equals(order.getStatus())) {
                order.setStatus(orderStatus);
                orderRepository.save(order);
            }
        });
    }

    @Override
    public Order findOrderById(Long orderId) {
        return orderRepository.findById(orderId).orElse(null);
    }

}
